package com.zhouqinuan.spring.cloud.develop.framework.demo.mongodb.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.zhouqinuan.spring.cloud.develop.framework.base.util.BeanUtil;
import com.zhouqinuan.spring.cloud.develop.framework.demo.mongodb.document.UserDocument;
import com.zhouqinuan.spring.cloud.develop.framework.demo.mongodb.repository.UserDocumentRepository;
import com.zhouqinuan.spring.cloud.develop.framework.demo.mongodb.req.AddUserDocumentReq;
import com.zhouqinuan.spring.cloud.develop.framework.demo.mongodb.req.UpdateUserDocumentReq;

@Service
public class UserDocumentService {

    @Autowired
    private UserDocumentRepository userDocumentRepository;

    public UserDocument getById(String id) {
        return userDocumentRepository.findById(id).orElse(null);
    }

    public UserDocument queryByName(String name) {

        return userDocumentRepository.getByName(name);
    }

    public UserDocument getByName(String name) {
        UserDocument userDocument = new UserDocument();
        userDocument.setName(name);
//        Example<UserDocument> example = Example.of(userDocument, ExampleMatcher.matching().withIgnorePaths("_class")); ##解决缺少_class字段时查不到记录的问题
        Example<UserDocument> example = Example.of(userDocument);

        return userDocumentRepository.findOne(example).orElse(null);
    }

    public UserDocument addUserDocument(AddUserDocumentReq req) {
        UserDocument userDocument = BeanUtil.mapToObject(req, UserDocument.class);

        return userDocumentRepository.insert(userDocument);
    }

    public UserDocument updateUserDocument(UpdateUserDocumentReq req) {
        UserDocument userDocument = BeanUtil.mapToObject(req, UserDocument.class);

        return userDocumentRepository.save(userDocument);
    }

    public Page<UserDocument> getByPage(String name, int page, int size) {
        UserDocument userDocument = new UserDocument();
        userDocument.setName(name);
        Example<UserDocument> example = Example.of(userDocument);

        Pageable pageable = PageRequest.of(page - 1, size); //特别注意

        return userDocumentRepository.findAll(example, pageable);
    }
}
